<template>
  <div class="base-chart" :id="props.id"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import * as echarts from "echarts";
import { BarChart } from "echarts/charts";
import { GridComponent } from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
echarts.use([GridComponent, BarChart, CanvasRenderer]);

const props = defineProps({
  id: String,
  options: Object,
});

const chartInstance = ref(null);
const chartDom = ref(null);
const resizeObserver = ref(null);

const initChart = () => {
  chartDom.value = document.getElementById(props.id);
  chartInstance.value = echarts.init(chartDom.value);
  chartInstance.value.setOption(props.options);
};

const resizeChart = () => {
  // chartInstance.value.resize();
};

onMounted(() => {
  initChart();
  // window.addEventListener("resize", resizeChart);
});

onBeforeUnmount(() => {
  // window.removeEventListener("resize", resizeChart);
  chartInstance.value?.dispose();
});

watch(
  () => props.options,
  (newOptions) => {
    chartInstance.value?.setOption(newOptions);
  },
  { deep: true }
);

defineExpose({
  getInstance: () => chartInstance.value,
  resize: resizeChart,
});
</script>

<style scoped>
.base-chart {
  width: 100%;
  height: 100%;
}
</style>
